<?php
declare (strict_types=1);

namespace app\course\logic\coupon\admin;

use app\admin\logic\system\Log;
use app\common\exception\LogicException;
use app\course\model\base\Course;
use app\course\model\coupon\admin\Coupon;
use app\course\model\coupon\admin\CouponOffline as CouponOfflineModel;

/**
 * 用户卡券逻辑层
 */
class CouponOffline extends CouponOfflineModel
{
    /**
     * 获取某个卡券的发放情况
     * Author   Martinsun<syh@sunyonghong.com>
     * Date 2020-05-13
     *
     * @return   [type]                         [description]
     */
    public function getListByCouponId(int $coupon_id)
    {
        return $this->where('__TABLE__.coupon_id', $coupon_id)->withJoin(['couponUser'], 'LEFT')->order('__TABLE__.create_time', 'DESC')->paginate($this->getListRows())->each(function ($item) {
            if ($item->status != 0) {
                $user = $item->couponUser->user;
                if ($user) {
                    $item->phone     = $user->phone;
                    $item->nick_name = $user->nick_name;
                }
            }
        });
    }

    /**
     * 生成实体卡券
     * Author   Martinsun<syh@sunyonghong.com>
     * Date 2020-05-15
     *
     * @param    [type]                         $coupon_id [description]
     * @param    [type]                         $user_id   [description]
     * @return   [type]                                    [description]
     */
    public function grant($coupon_id, $count = 1)
    {
        $coupon = app(Coupon::class)->where('id', $coupon_id)->find();
        if (!$coupon) {
            throw new LogicException('卡券不存在');
        }

        $datas = [];
        for ($i = 0; $i < $count; $i++) {
            $datas[] = [
                'coupon_id'   => $coupon_id,
                'coupon_type' => $coupon->coupon_type,
            ];
        }
        $coupon->count += $count;

        if (!$this->saveAll($datas) || !$coupon->save()) {
            throw new LogicException('实体卡生成失败');
        }
        switch ($coupon->coupon_type) {
            case 1:
                $type_text = '优惠券';
                break;
            case 2:
                $type_text = '打折卡';
                break;
            case 3:
                $type_text = '课程卡';
                break;
        }
        Log::write('生成实体' . $type_text, 'coupon_offline', 'create', true);

        return $this;

    }

    /**
     * 获取导出数据
     * Author: 亓官雨树 <lucky.max@foxmail.com>
     * Date: 22/02/11
     *
     * @param int $coupon_type
     * @return CouponOffline[]|array|\think\Collection
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function getExportData(int $coupon_type, array $where = [])
    {
        switch ($coupon_type) {
            case 1:
                $with      = ['coupon_minus'];
                $type_text = '优惠券';
                break;
            case 2:
                $with      = ['coupon_discount'];
                $type_text = '打折卡';
                break;
            case 3:
                $with      = ['coupon_course'];
                $type_text = '课程卡';
                break;

        }
        $map = [
            ['online', '=', 0],
            ['coupon_type', '=', $coupon_type],
            ['use_etime', '>', time()],
        ];
        if (count($where)) {
            foreach ($where as $key => $value) {
                array_push($map, [$key, '=', $value]);
            }
        }

        if (!request()->is_platform) array_push($map, ['mhm_id', '=', request()->mhm_id]);
        $ids = app(Coupon::class)->where($map)->column('id');
        if (!count($ids)) return false;
        $datas = $this->field('offline_code,coupon_id')->where('status', 0)->whereIn('coupon_id', $ids)->with($with)->select();
        if ($datas->isEmpty()) return false;
        $datas->each(function ($i) use ($coupon_type) {
            $i->use_time = $i->use_stime . ' - ' . $i->use_etime;
            if ($coupon_type == 3) $i->course_type_text = Course::getCourseTypeTextByType($i->course_type);
        });
        Log::write('导出实体' . $type_text, 'coupon_offline', 'export', true);
        return $datas;
    }
}
